package com.example.home_app.util

import android.content.Context
import android.content.SharedPreferences

/**
 * 这个是SharedPreferences的封装
 * Created by Administrator on
 */
class SPTool private constructor(context: Context) {

    fun putInt(key: String?, value: Int) {
        editor !!.putInt(key, value)
        editor !!.commit()
    }

    fun getInt(key: String?, defaultValue: Int): Int {
        return sp !!.getInt(key, defaultValue)
    }

    fun putLong(key: String?, value: Long?) {
        editor !!.putLong(key, value !!)
        editor !!.commit()
    }

    fun getLong(key: String?, defaultValue: Int): Long {
        return sp !!.getLong(key, defaultValue.toLong())
    }

    fun putString(key: String?, value: String?) {
        editor !!.putString(key, value)
        editor !!.commit()
    }

    fun getString(key: String?, defaultValue: String?): String? {
        return sp !!.getString(key, defaultValue)
    }

    fun putFloat(key: String?, value: Float) {
        editor !!.putFloat(key, value)
        editor !!.commit()
    }

    fun isKeyExist(key: String?): Boolean {
        return sp !!.contains(key)
    }

    fun getFloat(key: String?, defaultValue: Float): Float {
        return sp !!.getFloat(key, defaultValue)
    }

    fun putBoolean(key: String?, value: Boolean) {
        editor !!.putBoolean(key, value)
        editor !!.commit()
    }

    fun getBoolean(key: String?, defaultValue: Boolean): Boolean {
        return sp !!.getBoolean(key, defaultValue)
    }

    fun remove(key: String?) {
        editor !!.remove(key)
        editor !!.commit()
    }

    companion object {
        private lateinit var sp: SharedPreferences
        private var spManager: SPTool? = null
        private var editor: SharedPreferences.Editor? = null
        private const val SHARE_NAME = "info" //Preference文件名
        fun getInstance(context: Context): SPTool? {
            if (spManager == null || sp == null || editor == null) {
                spManager = SPTool(context)
            }
            return spManager
        }
    }

    init {
        sp = context.getSharedPreferences(SHARE_NAME, Context.MODE_PRIVATE)
        editor = sp.edit()
    }
}